package com.rent.message.ws;

import com.rent.common.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Service
@Slf4j
public class MessageSessionService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    
    /**
     * 核心：存储用户和会话的映射
     */
    /**
     * 存储用户和会话的映射
     */
    public void saveUserSession(String userId, String sessionId,String uuid) {
        try {
            // 用户 -> 多个session（支持多设备）
            String userKey = CommonConstant.USER_KEY + userId;
            redisTemplate.opsForSet().add(userKey, sessionId);

            // session -> 用户（断开时清理用）
            String sessionKey = CommonConstant.USER_SESSION + sessionId;
            redisTemplate.opsForValue().set(sessionKey, userId);

            // session -> 用户（断开时清理用）
            String uuidKey = CommonConstant.USER_SESSION_UUID + sessionId;
            redisTemplate.opsForValue().set(uuidKey, uuid);

            log.info("用户会话保存成功: userId={}, sessionId={}", userId, sessionId);
        } catch (Exception e) {
            log.error("保存用户会话失败", e);
        }
    }

    /**
     * 通过用户ID找所有会话
     */
    public Set<Object> getUserSessions(String userId) {
        try {
            String key = CommonConstant.USER_KEY + userId;
            Set<Object> sessions = redisTemplate.opsForSet().members(key);
            log.debug("获取用户会话: userId={}, sessions={}", userId, sessions);
            return sessions;
        } catch (Exception e) {
            log.error("获取用户会话失败", e);
            return Collections.emptySet();
        }
    }

    public Set<Object> getUserUuids(String userId) {
        try {
            Set<Object> userSessions = getUserSessions(userId);
            Set<Object> uuids = new HashSet<>();
            for (Object userSession : userSessions){
                String uuidKey = CommonConstant.USER_SESSION_UUID + userSession;
                uuids.add(redisTemplate.opsForValue().get(uuidKey));
            }
            log.debug("获取用户会话: userId={}, sessions={}", userId, uuids);
            return uuids;
        } catch (Exception e) {
            log.error("获取用户会话失败", e);
            return Collections.emptySet();
        }
    }


    
    /**
     * 用户断开连接时清理
     */
    public void removeSession(String sessionId) {
        // 通过session找用户
        String sessionKey = CommonConstant.USER_SESSION + sessionId;
        String uuidKey = CommonConstant.USER_SESSION_UUID + sessionId;
        String userId = (String) redisTemplate.opsForValue().get(sessionKey);



        if (userId != null) {
            // 从用户的会话集合中移除
            String userKey = CommonConstant.USER_KEY + userId;
            redisTemplate.opsForSet().remove(userKey, sessionId);
        }
        
        // 删除session映射
        redisTemplate.delete(sessionKey);
        redisTemplate.delete(uuidKey);
    }



    /**
     * 检查用户是否在线
     */
    public boolean isUserOnline(String userId) {
        String userKey = CommonConstant.USER_KEY + userId;
        Set<Object> sessions = redisTemplate.opsForSet().members(userKey);
        return sessions != null && !sessions.isEmpty();
    }

    /**
     * 获取在线用户数
     */
    public long getOnlineUserCount() {
        // 注意：这种方法在生产环境中可能需要优化
        Set<String> keys = redisTemplate.keys(CommonConstant.USER_KEY+"*");
        return keys != null ? keys.size() : 0;
    }

    /**
     * 广播消息给所有用户
     * TODO:逻辑修改
     */
    public void broadcastToAllUsers(Object message) {
        Set<String> userKeys = redisTemplate.keys(CommonConstant.USER_KEY+"*");
        if (userKeys != null) {
            for (String userKey : userKeys) {
                String userId = userKey.substring(CommonConstant.USER_KEY.length());
                Set<Object> sessions = redisTemplate.opsForSet().members(userKey);
                if (sessions != null) {
                    for (Object sessionId : sessions) {
                        simpMessagingTemplate.convertAndSendToUser(
                                sessionId.toString(),
                                "/queue/chat",
                                message);
                        // 这里需要 SimpMessagingTemplate，可以通过参数传入
                    }
                }
            }
        }
    }

}